﻿using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Ioc;
using GalaSoft.MvvmLight.Views;
using JiveMessenger.User;
using JiveMessenger.Utilities;
using System;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;

namespace JiveMessenger.ViewModels
{
    public class ViewModelCropAvatarPage : ViewModelCropImageBase
    {
        public override RelayCommand SaveCommand { get; set; }


        public ViewModelCropAvatarPage(IClient currentClient, INavigationService navService)
            : base(currentClient, navService)
        {
            SaveCommand = new RelayCommand(SaveAvatarCommandAction);
            //  AvatarImagePath = file.Path;
        }



        private async void SaveAvatarCommandAction()
        {
            ShowProgressOverlay = true;
            string newFileName = "";
            IRandomAccessStream stream = null;
            WriteableBitmap wb = null;// (WriteableBitmap)this.AvatarImageSource;
            try
            {
                if (_croppedData != null)
                {
                    //wb = new WriteableBitmap(AvatarImageSource.PixelWidth, AvatarImageSource.PixelHeight);
                    //await wb.SetSourceAsync(_croppedData);
                    wb = await CropBitmap.CreateWritableBitmap(_croppedData);
                }
                else
                {
                    wb = await CropBitmap.CreateWritableBitmap(OriginalImageFile);
                }


                wb = wb.Resize(400, 400, WriteableBitmapExtensions.Interpolation.Bilinear);
                stream = await SaveToStream(wb);
                //var bitmap = await CropBitmap.ResizeBitmapAsync(_croppedData, new Size(200, 200));
                //var stream = await SaveToStream(bitmap);
                //  var stream = await CropBitmap.ResizeBitmapAsync(_croppedData, 200, 200);
                byte[] data = await StaticMethods.LoadImageData(stream);
                string md5 = await StaticMethods.ComputeMD5Async(data);
                string ext = Path.GetExtension(OriginalImageFile.Name);
                newFileName = md5 + ext;
                StorageFolder folder = await StaticMethods.GetAvatarStorageFolderForUser(_currentClient.CurrentUserInfo.UserName);
                //  StorageFile newFile = await folder.CreateFileAsync(newAvatarName, CreationCollisionOption.ReplaceExisting);
                //await CropBitmap.SaveCroppedBitmapAsync(OriginalImageFile, newFile, new Point(CropLeft, CropTop), new Size(CropWidth, CropHeight));
                await StaticMethods.SaveImageToStorage(folder, data, newFileName, CreationCollisionOption.ReplaceExisting);
                _currentClient.UserSettings.Avatar = new JmShared.Avatar()
                {
                    Extension = ext,
                    Hash = md5
                };

                _currentClient.Connection.SendCommand(_currentClient.UserSettings, JmShared.ClientCommands.WpSettings);
                _navigationService.GoBack();
            }
            finally
            {
                if (stream != null)
                    stream.Dispose();
                ShowProgressOverlay = false;
            }
        }


        public override void Cleanup()
        {
            base.Cleanup();
            SimpleIoc.Default.Unregister<ViewModelCropAvatarPage>(VmHelper.Locator.ViewModelCropAvatarPageKey);
            VmHelper.Locator.ViewModelCropAvatarPageKey = System.Guid.NewGuid().ToString();

        }
    }
}
